package com.liming.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liming.common.result.LMResult;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author liming
 * @date 2025/1/8
 */
public class ResToJsonWriteUtils {

    public static Mono<Void> write(ServerWebExchange exchange) throws JsonProcessingException {
        ServerHttpResponse response = setResProp(exchange, HttpStatus.UNAUTHORIZED);

        LMResult<Object> error = LMResult.error("未认证");
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = objectMapper.writeValueAsBytes(error);

        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }

    @NotNull
    private static ServerHttpResponse setResProp(ServerWebExchange exchange, HttpStatus httpStatus) {
        // 不放行，返回错误响应
        ServerHttpResponse response = exchange.getResponse();
        // 设置状态码为401 UNAUTHORIZED 设置状态码为403 Forbidden
        response.setStatusCode(httpStatus);
        // 设置响应内容为JSON
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        return response;
    }

    public static Mono<Void> write(ServerWebExchange exchange, String msg) throws JsonProcessingException {
        ServerHttpResponse response = setResProp(exchange, HttpStatus.UNAUTHORIZED);

        LMResult<Object> error = LMResult.error(msg);
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = objectMapper.writeValueAsBytes(error);

        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }
}
